package com.davidhigenbottam.HeatMap.server;

import java.util.HashMap;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.davidhigenbottam.HeatMap.client.HeatmapService;
import com.davidhigenbottam.HeatMap.shared.Query;
import com.davidhigenbottam.HeatMap.shared.Results;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class HeatmapServiceImpl extends RemoteServiceServlet implements
		HeatmapService {

	static final String USER_SESSION_KEY = "USERNAME";

	private static final HashMap<String, String> usersPasswords = new HashMap<String, String>();
	static {
		usersPasswords.put("test", "test");
		usersPasswords.put("user1", "user1");
		usersPasswords.put("janet", "janet");
		usersPasswords.put("david", "david");
	}

	protected static final Logger log = Logger
			.getLogger(HeatmapServiceImpl.class.getName());

	@Override
	public Results getResults(Query query)
			throws IllegalArgumentException {

		return DataCache.getInstance().getData(query).getResults();

	}



//	@Override
//	public List<Institution> institutions(Query query)
//			throws IllegalArgumentException {
//
//		ProvinceDataCache cache = ProvinceDataCache.getInstance();
//		ProvinceData provinceData = cache.getProvinceData(query, isLocalMode());	
//		Province p = provinceData.getProvince(query.getProvince());
//		return provinceData.getInstitutionList(p);
//	}

	@Override
	public Boolean checkLoggedIn() {
		HttpServletRequest request = this.getThreadLocalRequest();
		HttpSession session = request.getSession();
		// session.getId();
		String username = (String) session.getAttribute(USER_SESSION_KEY);
		if (username == null)
			return Boolean.FALSE;
		else
			return Boolean.TRUE;
	}

	@Override
	public Boolean authenticate(String username, String password) {
		if (username == null || username.length() == 0)
			return Boolean.FALSE;
		if (password == null || password.length() == 0)
			return Boolean.FALSE;

		String pwd = usersPasswords.get(username);
		if (password.equals(pwd)) {
			HttpServletRequest request = this.getThreadLocalRequest();
			HttpSession session = request.getSession();
			session.setAttribute(USER_SESSION_KEY, username);
			log.info(username+ " logged in!!");
			return Boolean.TRUE;

		} else {
			return Boolean.FALSE;
		}
	}

}
